/**
 * axios 二次封装
 */
import instance from './instance'

function server (this: any) {
  this.instance = instance
  this.nowHandle = null
}

server.prototype.v = function (vm: any) {
  this.nowHandle = vm
}

interface Conf {
  type: 'get',
  data: {},
  bindName?: any,
  success: any
}
server.prototype.sendMgs = function (moduleName: any, urlKey: string, url: string, config: Conf) {
  const _this = this
  const conf = config || {}
  const type = conf.type || 'get'
  const data = conf.data || {}
  const bindName = conf.bindName || urlKey

  // 分成2个模块：数据处理/效果处理（比如loading）
  const before = function (res: any) {
    console.log(res)
    _this[moduleName][urlKey].status = 'ready'
  }

  const defaultFn = function (res: any) {
    _this.nowHandle[bindName] = res.data
  }

  const success = conf.success || defaultFn

  // 并行
  if (this[moduleName][urlKey].status === 'ready') {
    this.instance[type](url).then(before).then(success)
    this[moduleName][urlKey].status = 'waiting'
  }
}

// 接口api化
server.prototype.parseRouter = function (this: any, moduleName: string, options: any) {
  this[moduleName] = {}
  Object.keys(options).forEach((urlKey) => {
    this[moduleName][urlKey] = this.sendMgs.bind(this, moduleName, urlKey, options[urlKey])

    // 防重复请求，每一个api给个status
    this[moduleName][urlKey].status = 'ready'
  })
}

export default new (server as any)()
